package com.southminority.ethnic.controller.admin.document;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.dto.DocumentDTO;
import com.southminority.ethnic.service.document.DocumentService;
import com.southminority.ethnic.controller.document.vo.DocumentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 古籍文献管理后台控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "🛠️ 古籍文献管理后台", description = "用于管理员增、删、改、查古籍文献的后台接口")
@RestController
@RequestMapping("/admin/document")
@CrossOrigin
public class DocumentAdminController {

    private final DocumentService documentService;

    public DocumentAdminController(DocumentService documentService) {
        this.documentService = documentService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询古籍文献列表", description = "管理员分页查询古籍文献，支持按关键词、分类、类型、朝代、状态等多条件筛选")
    @Parameters({
        @Parameter(name = "page", description = "当前页码", example = "1"),
        @Parameter(name = "size", description = "每页显示数量", example = "10"),
        @Parameter(name = "keyword", description = "搜索关键词（标题、作者、描述等）", example = "水书"),
        @Parameter(name = "categoryId", description = "分类ID", example = "1"),
        @Parameter(name = "documentType", description = "文献类型", example = "古籍"),
        @Parameter(name = "dynasty", description = "朝代", example = "清朝"),
        @Parameter(name = "status", description = "状态：1-已发布, 0-草稿, -1-已删除", example = "1")
    })
    @ApiResponse(responseCode = "200", description = "查询成功")
    public R<PageResult<DocumentVO>> getDocumentPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String documentType,
            @RequestParam(required = false) String dynasty,
            @RequestParam(required = false) Integer status) {
        try {
            PageResult<DocumentVO> pageResult = documentService.getDocumentPage(page, size, keyword, categoryId, documentType, dynasty, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询古籍文献失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建古籍文献", description = "新增一篇古籍文献")
    @ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = DocumentVO.class)))
    @ApiResponse(responseCode = "400", description = "请求参数校验失败")
    public R<DocumentVO> createDocument(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "古籍文献信息", required = true) @Valid @RequestBody DocumentDTO documentDTO) {
        try {
            log.info("管理员创建古籍文献: {}", documentDTO.getTitle());
            DocumentVO documentVO = documentService.createDocument(documentDTO);
            return R.ok(documentVO);
        } catch (Exception e) {
            log.error("创建古籍文献失败", e);
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "更新古籍文献", description = "更新指定ID的古籍文献信息")
    @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = DocumentVO.class)))
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<DocumentVO> updateDocument(
            @Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "古籍文献信息", required = true) @Valid @RequestBody DocumentDTO documentDTO) {
        try {
            log.info("管理员更新古籍文献: ID={}, 标题={}", id, documentDTO.getTitle());
            DocumentVO documentVO = documentService.updateDocument(id, documentDTO);
            return R.ok(documentVO);
        } catch (Exception e) {
            log.error("更新古籍文献失败", e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除古籍文献", description = "逻辑删除指定ID的古籍文献")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<Boolean> deleteDocument(@Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id) {
        try {
            log.info("管理员删除古籍文献: ID={}", id);
            boolean result = documentService.deleteDocument(id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除古籍文献失败", e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除古籍文献", description = "批量逻辑删除古籍文献")
    @ApiResponse(responseCode = "200", description = "删除成功")
    public R<Boolean> batchDeleteDocument(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "古籍文献ID列表", required = true) @RequestBody List<Long> ids) {
        try {
            log.info("管理员批量删除古籍文献: IDs={}", ids);
            boolean result = documentService.batchDeleteDocument(ids);
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除古籍文献失败", e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取古籍文献详情（管理端）", description = "获取单个古籍文献的详细信息，可能包含未发布的字段")
    @ApiResponse(responseCode = "200", description = "获取成功")
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<DocumentVO> getDocumentDetail(@Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id) {
        try {
            DocumentVO documentVO = documentService.getDocumentDetail(id);
            return R.ok(documentVO);
        } catch (Exception e) {
            log.error("获取古籍文献详情失败", e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新古籍文献状态", description = "更新文献的发布状态")
    @ApiResponse(responseCode = "200", description = "更新成功")
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<Boolean> updateDocumentStatus(
            @Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "新状态：1-已发布，0-草稿，-1-已删除", required = true, example = "1", schema = @Schema(allowableValues = {"1", "0", "-1"})) @RequestParam Integer status) {
        try {
            log.info("管理员更新古籍文献状态: ID={}, Status={}", id, status);
            boolean result = documentService.updateDocumentStatus(id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新古籍文献状态失败", e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }

    @PutMapping("/featured/{id}")
    @Operation(summary = "设置首页展示", description = "设置或取消某篇文献在首页的展示")
    @ApiResponse(responseCode = "200", description = "设置成功")
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<Boolean> setDocumentFeatured(
            @Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "是否首页展示：1-是，0-否", required = true, example = "1", schema = @Schema(allowableValues = {"1", "0"})) @RequestParam Integer isFeatured) {
        try {
            log.info("管理员设置古籍文献首页展示: ID={}, IsFeatured={}", id, isFeatured);
            boolean result = documentService.setDocumentFeatured(id, isFeatured);
            return R.ok(result);
        } catch (Exception e) {
            log.error("设置古籍文献首页展示失败", e);
            return R.fail("设置失败: " + e.getMessage());
        }
    }

    @PutMapping("/homepage-order/{id}")
    @Operation(summary = "设置首页展示顺序", description = "调整文献在首页的显示顺序，数字越小越靠前")
    @ApiResponse(responseCode = "200", description = "设置成功")
    @ApiResponse(responseCode = "404", description = "文献不存在")
    public R<Boolean> setDocumentHomepageOrder(
            @Parameter(description = "古籍文献ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "首页展示顺序", required = true, example = "1") @RequestParam Integer homepageOrder) {
        try {
            log.info("管理员设置古籍文献首页展示顺序: ID={}, HomepageOrder={}", id, homepageOrder);
            boolean result = documentService.setDocumentHomepageOrder(id, homepageOrder);
            return R.ok(result);
        } catch (Exception e) {
            log.error("设置古籍文献首页展示顺序失败", e);
            return R.fail("设置失败: " + e.getMessage());
        }
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有古籍文献列表（不分页）", description = "获取所有古籍文献的完整列表，用于后台某些选择器场景")
    @ApiResponse(responseCode = "200", description = "获取成功")
    public R<List<DocumentVO>> getAllDocumentList() {
        try {
            List<DocumentVO> documentList = documentService.getAllDocumentList();
            return R.ok(documentList);
        } catch (Exception e) {
            log.error("获取所有古籍文献列表失败", e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }

    @GetMapping("/homepage")
    @Operation(summary = "获取首页展示文献列表（管理端）", description = "获取所有被设置为在首页展示的古籍文献列表")
    @ApiResponse(responseCode = "200", description = "获取成功")
    public R<List<DocumentVO>> getHomepageDocumentList() {
        try {
            List<DocumentVO> documentList = documentService.getHomepageDocumentList();
            return R.ok(documentList);
        } catch (Exception e) {
            log.error("获取首页展示古籍文献列表失败", e);
            return R.fail("获取首页展示古籍文献数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/test")
    @Operation(summary = "测试接口连通性")
    @ApiResponse(responseCode = "200", description = "服务正常")
    public R<String> test() {
        return R.ok("古籍文献管理后台服务正常");
    }
} 
